package io.noties.markwon.base.core.spans

import android.text.style.LeadingMarginSpan

import android.graphics.Canvas
import android.graphics.Paint
import android.text.Layout
import com.gitee.wsl.ext.base.setAlpha
import io.noties.markwon.theme.MarkwonTheme

class ThematicBreakSpan(private val theme: MarkwonTheme) : LeadingMarginSpan {
    private val rect = ObjectsPool.rect()
    private val paint = ObjectsPool.paint()
    override fun getLeadingMargin(first: Boolean): Int {
        return 0
    }

    override fun drawLeadingMargin(
        c: Canvas,
        p: Paint,
        x: Int,
        dir: Int,
        top: Int,
        baseline: Int,
        bottom: Int,
        text: CharSequence,
        start: Int,
        end: Int,
        first: Boolean,
        layout: Layout
    ) {
        val middle = top + (bottom - top) / 2
        paint.set(p)
        applyThematicBreakStyle(paint)
        val height = (paint.strokeWidth + .5f).toInt()
        val halfHeight = (height / 2f + .5f).toInt()
        val left: Int
        val right: Int
        if (dir > 0) {
            left = x
            right = c.width
        } else {
            left = x - c.width
            right = x
        }
        rect[left, middle - halfHeight, right] = middle + halfHeight
        c.drawRect(rect, paint)
    }

    private fun applyThematicBreakStyle(paint: Paint) {
        val color: Int = if (theme.colorTheme.thematicBreakColor != 0L) {
            theme.colorTheme.thematicBreakColor.toInt()
        } else {
            paint.color.setAlpha(THEMATIC_BREAK_DEF_ALPHA)
        }
        paint.color = color
        paint.style = Paint.Style.FILL
        if (theme.typography.thematicBreakHeight >= 0) {
            paint.strokeWidth = theme.typography.thematicBreakHeight.toFloat()
        }
    }

    companion object {
        protected const val THEMATIC_BREAK_DEF_ALPHA = 25
    }
}